package com.linsen.core.common.util;

import lombok.experimental.UtilityClass;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** SHA加密算法 */
@UtilityClass
public class ShaUtil {
    private final String ENC_NAME="SHA-256";

    public static String encrypt(String strSrc){
        return encrypt(strSrc,ENC_NAME);
    }

    /**
     * 对字符串加密,加密类型可指定使用MD5,SHA-1,SHA-256,默认使用SHA-256
     * SHA256加密算法
     * @param strSrc
     *            要加密的字符串
     * @param encName
     *            加密类型
     * @return
     */
    public static String encrypt(String strSrc,String encName) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            // to HexString
            strDes = bytes2Hex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
}
